/*
* SMILParser
*
* Version 1.0
*
* Programmers: Jesse Louderback, Noah Pham, Chad Carpenter, and Marc Hindman
*/
package comm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMS_Listener extends BroadcastReceiver {
	private final String TAG = "SMILDIAL";
	Notify notify;
	Context context;
	protected final static String FILE_LOC = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/SMIL Messages/";
	Timer timer = new Timer();
	boolean messageReceived = false;
	FileWriter fos = null;
	String fileName = "";
	String FromAddress = "";

	@Override
	public void onReceive(Context context, Intent intent) {
		
		// ---get the SMS message passed in---
		Bundle bundle = intent.getExtras();
		SmsMessage[] msgs = null;
		String str = "";
		String fromAdd = "";
		
		if (bundle != null) {
			
			// ---retrieve the SMS message received---
			Object[] pdus = (Object[]) bundle.get("pdus");
			msgs = new SmsMessage[pdus.length];
			for (int i = 0; i < msgs.length; i++) {
				msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				fromAdd = msgs[i].getOriginatingAddress();
				str += msgs[i].getMessageBody().toString();
			}
			if (str.length() > 6) {
				String startTag = str.substring(0, 6).toLowerCase();
				if (startTag.equals("<smil>")) {
					Log.e(TAG, "Inside if( <SMIL> )");
					
					FromAddress = fromAdd;
					messageReceived = true;
					this.abortBroadcast();
					File sdCard = Environment.getExternalStorageDirectory();
					try {
						File dir = new File(sdCard.getAbsolutePath()+ "/SMIL Messages");
						dir.mkdirs();
						fileName = FromAddress;
						

						Log.e(TAG, "Pre Make File");

						File file = new File(dir, fileName + getMaxFileNumber() + ".smil"); 

						Log.e(TAG, "Post Make File");
						
						fos = new FileWriter(file, false);
						fos.write(str);
						setTimer();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else if (messageReceived && fromAdd.equals(FromAddress)){
					Log.e(TAG, "Inside: messageRecieved and " + fromAdd + "=" + FromAddress);
					
					try {
						this.abortBroadcast();
						fos.append(str);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void displayNotice() {
		String Title = "Msg Received";
		String NoteMessage = "You have recieved a SMIL Message.";
		notify.sendNotice(Title, NoteMessage, fileName);
	}
	
	public String getMaxFileNumber() {
		int max = 0;      
	    ArrayList<String> listOfMessages = getListOfMessages();
	    Iterator<String> itr = listOfMessages.iterator();
	    while (itr.hasNext()) {
	    	String nextFile = itr.next().toString();
	    	nextFile = nextFile.toString().substring(nextFile.length() - 9, (nextFile.length() - 5));
	    	boolean isNumber = true;
	        for (int i = 0; i < nextFile.length(); i++) {
	            if (!Character.isDigit(nextFile.charAt(i))) {
	            	isNumber = false;
	            }
	        }
	        if (isNumber == true) {
	           	int intPortion = Integer.parseInt(nextFile);
	            	
	           	if (intPortion > max) {
	           		max = intPortion;
	           	}
	        }          	 
	    }  
	    
	    max++;
		return String.format(" _" + "%04d", max);//Return the max + 1 for new file for example: "_0002"
	}

	public void setNotificationMrg(Notify notificationMgr) {
		this.notify = notificationMgr;
	}

	public void setContext() {
		context = notify.getContex();
	}

	private void setTimer() {
		timer.schedule(new TimerTask() {
			public void run() {
				messageReceived = false;
				try {
					FromAddress = "";
					fos.close();
					fileName = "";
					displayNotice();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, 60000);
	}
	
	private ArrayList<String> getListOfMessages() {
		FilenameFilter smilFilter = new FilenameFilter() {     
    		File f;
    		
    		public boolean accept(File dir, String name) {     
    			if (name.endsWith(".smil") || name.endsWith(".smil")) {             
    				return true;
    			}         
    			f = new File(dir.getAbsolutePath()+"/"+name);          
    			return f.isDirectory();     
			} 
    	};
    	
		File dir = new File(FILE_LOC);
        File[] messageList = dir.listFiles(smilFilter);
        
        ArrayList<String> messages = new ArrayList<String>();           
        
        for (int i = 0; i < messageList.length; i++) {
        	messages.add(messageList[i].getName());
        }
        
		return messages;
	}
}
